package org.zjx.task.tasks;

import org.zjx.battle.BattleManager;
import org.zjx.battle.entity.Battle;
import org.zjx.common.command.*;
import org.zjx.common.command.battle.ExitCommand;
import org.zjx.common.entity.Address;
import org.zjx.common.entity.Quest;
import org.zjx.common.model.RouteProperties;
import org.zjx.task.Task;
import org.zjx.task.TaskType;
import org.zjx.team.ITeam;
import org.zjx.team.TeamManager;
import org.zjx.team.TeamType;
import org.zjx.util.TaskMatcher;

import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CatchGhostsTask extends Task {
    public CatchGhostsTask() {
        super("常规任务", "捉鬼", TaskType.RANDOM);
        totalReps = 200;
        initReceiveNpc();
    }

    @Override
    public List<String> getTemplates() {
        List<String> strings = new ArrayList<>();
        strings.add("钟馗抓鬼（第{次数}个）：去{地址}附近抓{怪物名称}。");
        strings.add("钟馗抓鬼（第{次数}个）：去{地址}处抓{怪物名称}。");

        return strings;
    }

    private int matchTemplate(String input) {
        if (input.isEmpty()) {
            return -1;
        }
        for (int i = 0; i < templates.size(); i++) {
            String template = templates.get(i);
            TaskMatcher.MatchResult matchResult = TaskMatcher.matchTask(template, input);
            if (matchResult.isMatched()) {
                return i; // 返回匹配的模板索引（从0开始）
            }
        }
        return -1; // 无匹配
    }

    @Override
    public ICommand getCommand(RouteProperties routeProperties) {

        //单人队伍
        ITeam iteam = TeamManager.getInstance().addTeamMember(routeProperties.getPlayerId(), TeamType.SINGLE);

        BattleManager.getInstance().updateBattleRouteProperties(routeProperties);
        boolean isLeader = iteam.getLeader().equals(routeProperties.getPlayerId());

        if (isLeader) {
            if (!iteam.allPlayersJoined()) {
                //等待队伍组齐
                return new WaitCommand(2);
            } else if (routeProperties.getQueues() == null || routeProperties.getQueues().isEmpty()) {
                //采集全部任务
                return new GatherQuestCommand();
            } else {
                //执行任务逻辑
                return doTask(routeProperties);
            }
        } else {
            if (!routeProperties.isInTeam()) {
                //TODO 安排队伍
                //TODO 返回入队操作，携带队长坐标
            }

            //TODO  根据血量蓝量判断恢复
            //等待进入战斗
            return new WaitCommand(1);
        }
    }

    public ICommand doTask(RouteProperties routeProperties) {
        //判断身上是否有抓鬼任务
        Quest quest = containsQuest(routeProperties.getQueues());

        if (quest == null || quest.getName().isEmpty()) {
            if (routeProperties.getSyxTime() == 0 || System.currentTimeMillis() > routeProperties.getSyxTime()) {
                //过时,使用摄妖香
                return new UseItemCommand("摄妖香", null);
            }
            //领取任务
            return new ReceiveQuestCommand(npcAddress, new Address("地府", 42, 56), dialogues);
        }
        int index = matchTemplate(quest.getContent());
        if (index == 0) {
            return execute_0(routeProperties, quest);
        } else if (index == 1) {
            return execute_1(routeProperties, quest);
        }
        //匹配错误,退出游戏
        return new ExitCommand();
    }

    public ICommand execute_0(RouteProperties routeProperties, Quest quest) {
        if (!quest.isCorrect()) {
            //修正任务,使用天眼通符
            return new CorrectCommand();
        } else {
            TaskMatcher.MatchResult result = TaskMatcher.matchTask(templates.get(0), quest.getContent());
            String location = "";  //鬼地址
            String name = "";  //鬼名称
            for (TaskMatcher.Keyword keyword : result.getKeywords()) {
                if (keyword.getPlaceholder().equals("地址")) location = keyword.getKeyword();
                if (keyword.getPlaceholder().equals("怪物名称")) name = keyword.getKeyword();
            }

            //寻路+点击怪物
            Address parseAddress = parseAddress(location);
            return new AttackMonsters(parseAddress, name);
        }
    }

    public ICommand execute_1(RouteProperties routeProperties, Quest quest) {
        if (!quest.isCorrect()) {
            //修正任务,使用天眼通符
            return new CorrectCommand();
        } else {
            TaskMatcher.MatchResult result = TaskMatcher.matchTask(templates.get(1), quest.getContent());
            String location = "";  //鬼地址
            String name = "";  //鬼名称
            for (TaskMatcher.Keyword keyword : result.getKeywords()) {
                if (keyword.getPlaceholder().equals("地址")) location = keyword.getKeyword();
                if (keyword.getPlaceholder().equals("怪物名称")) name = keyword.getKeyword();
            }

            //寻路+点击怪物
            Address parseAddress = parseAddress(location);
            return new AttackMonsters(parseAddress, name);
        }
    }

    public void initReceiveNpc() {
        npcAddress = new Address("地府", 44, 56);
        List<String> strings = new ArrayList<>();
        strings.add("好的，我帮你。");
        dialogues = strings;
    }


    public static Address parseAddress(String input) {
        // 正则表达式匹配模式：地址名称 + x坐标 + 中英文逗号 + y坐标
        // 支持："江南野外45,78"、"江南野外 45, 78"、"女儿村93，72"、"女儿村93， 72"等格式
        Pattern pattern = Pattern.compile("^(.*?)(\\d+)\\s*[，,]\\s*(\\d+)$");
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            String city = matcher.group(1).trim();  // 获取地址名称并去除前后空格
            int x = Integer.parseInt(matcher.group(2));  // 获取x坐标
            int y = Integer.parseInt(matcher.group(3));  // 获取y坐标

            return new Address(city, x, y);
        } else {
            throw new IllegalArgumentException("输入的地址格式不正确，应为'地址x,y'或'地址x，y'格式，例如：'江南野外45,78'或'女儿村93，72'");
        }
    }

}
